using System;
using System.Collections.Generic;
using System.Linq;

namespace ProjectEuler.Core
{
    public class Problem44 : IProjectEulerProblem
    {
        public long CalculateResult()
        {
            return GetPentagonals()
                .Take(3000)
                .SelectMany((p, i) => GetPentagonals().Take(i)
                    .Where(q => IsPentagonal(p + q))
                    .Select(q => p - q))
                .Where(d => IsPentagonal(d))
                .Min();
        }

        public IEnumerable<long> GetPentagonals()
        {
            long i = 1;
            while (true)
            {
                yield return GetPentagonal(i++);
            }
        }

        public long GetPentagonal(long index)
        {
            return (index * (3 * index - 1)) / 2;
        }

        public bool IsPentagonal(double value)
        {
            return ((Math.Sqrt(24 * value + 1) + 1) / 6) % 1.0 == 0.0;
        }

        public int Number
        {
            get { return 44; }
        }

        public string Description
        {
            get
            {
                return "Find the pair of pentagonal numbers, Pj and Pk, for which their sum and difference is pentagonal and D = |Pk  Pj| is minimised; what is the value of D?";
            }
        }

        public string Answer
        {
            get { return CalculateResult().ToString(); }
        }
    }
}